/*
 * This servlet prepares the lesson.jsp page. It loads the content for that specific lesson.
 * it also loads the live lesson (if it is set as live)
 */
package controllers.classes;

import classes.Breadcrumbs;
import classes.HibernateUtil;
import dao.AssignmentHandinDao;
import dao.ChatDao;
import dao.CourseDao;
import dao.FileDao;
import dao.CourseDao;
import dao.EmployeeDao;
import dao.LessonDao;
import dao.LiveLessonDao;
import dao.NoteDao;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.AssignmentHandin;
import models.Chat;
import models.Course;
import models.Employee;
import models.Files;
import models.Lesson;
import models.LiveLesson;
import models.Note;
import models.User;

/**
 *
 * @author Achie
 */
public class LectureController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        long lessonid = Long.parseLong(request.getParameter("id"));

        HibernateUtil hu = new HibernateUtil();

        //----------------------------------------------------------------------
        //Get lesson
        //----------------------------------------------------------------------
        LessonDao ld = new LessonDao(hu.openSession());
        Lesson lesson = ld.get(lessonid);
        request.setAttribute("lesson", lesson);

        //----------------------------------------------------------------------
        //Get files from this specific lesson
        //----------------------------------------------------------------------
        FileDao fd = new FileDao(hu.openSession());
        List<Files> files = fd.findAllFilesInLesson(lessonid);
        request.setAttribute("file", files); //all files

        List<Files> viewfiles = new ArrayList<Files>(); //documents and presentations
        List<Files> presentation = new ArrayList<Files>(); //presentations
        List<Files> document = new ArrayList<Files>(); //documents
        List<Files> assignment = new ArrayList<Files>(); //assignments from lesson

        //put files (docs and presentations) in viewfiles list
        for (int i = 0; i < files.size(); i++) {
            if (files.get(i).getType().equals("ordinary")) {
                viewfiles.add(files.get(i));
            }
        }

        //put files (assignments) in assignment list
        for (int i = 0; i < files.size(); i++) {
            if (files.get(i).getType().equals("assignment")) {
                assignment.add(files.get(i));
            }
        }

        //-------------------------------------
        //Prepare first file, set as mainfile
        //-------------------------------------
        Files mainfile;
        if (viewfiles.size() > 0) {
            mainfile = viewfiles.get(0); //get the first file
        } else {
            mainfile = null;
        }

        if (request.getParameter("viewfileid") != null) { //if file is selected
            if (request.getParameter("viewfileid").equals("-")) { //if file equals -, set the mainfile as null
                mainfile = null;
            } else {
                mainfile = fd.get(Long.parseLong(request.getParameter("viewfileid")));
            }
        }

        //-------------------------------------
        //Prepare saved note
        //-------------------------------------
        NoteDao nd = new NoteDao(hu.openSession());
        HttpSession ses = request.getSession(); //get user id
        User user = (User) ses.getAttribute("user");

        long userid = 0;
        if (request.getParameter("isFree") != null) { //checks whether it's a free lesson, if it is, set the attribute as true
            request.setAttribute("isFree", true);
            if (user == null) { //check if it's a guest, if true..
                request.setAttribute("isGuest", true); //set attribute whether a guest is logged in or not
            }
        } else { //not a free lesson
            userid = user.getMember_id();
        }

        //Get notes via the lesson and user
        List<Note> notes = nd.findAllByUserAndLesson(userid, lessonid);
        Note note = null;
        if (notes.size() > 0) {
            note = notes.get(0);
        }

        //-------------------------------------
        //Get the students handed in assignments
        //-------------------------------------
        AssignmentHandinDao ash = new AssignmentHandinDao(hu.openSession());
        List<AssignmentHandin> handedassignments = ash.findAllByStudent(userid);


        //-------------------------------------
        //Get live object from lesson
        //-------------------------------------
        if (lesson.isLiveLesson()) {
            prepareLiveLesson(lesson, request);
        }
        //-------------------------------------
        //Prepare request attributes
        //-------------------------------------
        request.setAttribute("mainfile", mainfile);
        request.setAttribute("assignment", assignment);
        request.setAttribute("handedassignments", handedassignments);
        request.setAttribute("viewfiles", viewfiles);
        request.setAttribute("note", note);

        long courseid = lesson.getCourse().getId();

        CourseDao cdao = new CourseDao(hu.getSessionFactory().openSession());
        Course course = cdao.get(courseid);

        hu.close(); //close connection

        // Breadcrumbs
        Breadcrumbs[] breadcrumbs = {
            new Breadcrumbs("Index", "Home"),
            new Breadcrumbs("Category", "Course catalog"),
            new Breadcrumbs("Course?courseid=" + course.getId(), course.getName()),
            new Breadcrumbs("CourseLesson?courseid=" + course.getId(), "Lessons"),
            new Breadcrumbs("LectureController?courseid=" + course.getId() + "&id=" + lesson.getId(), lesson.getName())
        };
        request.setAttribute("breadcrumbs", breadcrumbs);

        RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/lesson.jsp");
        dispatcher.forward(request, response);
    }

    /*
     * This method is executed if the lesson is a live lesson
     */
    public void prepareLiveLesson(Lesson lesson, HttpServletRequest request) {
        HibernateUtil hu = new HibernateUtil();

        LiveLessonDao lld = new LiveLessonDao(hu.openSession());
        LiveLesson liveLesson = lld.getLiveLessonFromLessonId(lesson.getId());
        String embedStream = liveLesson.getEmbedStream();

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
        boolean isTeacher = false; //checks whether the current member is logged in as the teacher for that lesson

        //get the chat list
        ChatDao cd = new ChatDao(hu.openSession());
        List<Chat> chatlist = cd.findAllByLesson(lesson.getId(), "chat");

        //----------------------------------------------------------------------
        //Checks if a teacher is currently accessing the live lesson
        //----------------------------------------------------------------------
        EmployeeDao ed = new EmployeeDao(hu.openSession());
        List<Employee> teachers = ed.findAllByCourseId(lesson.getCourse().getId());
        HttpSession ses = request.getSession(); //current member role;
        String userrole = (String) ses.getAttribute("userrole");

        if (userrole != null) {
            if (userrole.equals("Teacher")) {
                User currentusr = (User) ses.getAttribute("user");
                for (int i = 0; i < teachers.size(); i++) {
                    if (teachers.get(i).getId() == currentusr.getMember_id()) { //if the current user is a teacher for the course
                        isTeacher = true;
                    }
                }
            } else if (userrole.equals("Administrator")) { //or if it is an admin
                isTeacher = true;
            } else {
                isTeacher = false;
            }
        } else {
            isTeacher = false;
        }
        //----------------------------------------------------------------------
        //Set attributes
        //----------------------------------------------------------------------
        String date_text = sdf.format(liveLesson.getDate().getTime());
        request.setAttribute("liveLesson", liveLesson);
        request.setAttribute("timeAndDate", date_text);
        request.setAttribute("chatlist", chatlist);
        request.setAttribute("isTeacher", isTeacher);
        request.setAttribute("embedStream", embedStream);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
